package com.hadoop.mapReduce.wordCountMine.ioDemo;

import com.hadoop.mapReduce.wordCountMine._01MyContext;
import com.hadoop.mapReduce.wordCountMine._02MyMapper;

import java.io.*;
import java.util.Map;
import java.util.Set;


public class IO_WCApp {

    public static void main(String[] args) throws Exception {

        FileReader fileReader = new FileReader("data/pride-and-prejudice.txt");
        BufferedReader br = new BufferedReader(fileReader);

        //处理每一行英文语句
        _02MyMapper mapper = new _03WordCountMapper();
        //创建仓库
        _01MyContext context = new _01MyContext();

        //每一行英文语句
        String line = null;
        while ((line = br.readLine()) != null) {
            //处理每一行英文语句,并把结果存入仓库
            mapper.map(line, context);
        }


        br.close();
        fileReader.close();

        Map<Object, Object> contextMap = context.getCacheMap();

        //把仓库 的数据写入result.txt文件

        // 1.构建要写的文件对象
        File file = new File("data/result.txt");
        try {
            // 2.构建文件输出流对象(构造时定义为追加内容)
            Writer writer = new FileWriter(file, false);
            // 3.定义输出内容
            Set<Map.Entry<Object, Object>> entries = contextMap.entrySet();
            // 4.把内容写入文件
            for(Map.Entry<Object, Object> entry : entries) {
                //key->The value-> 1
                writer.write((entry.getKey().toString() + " \t " + entry.getValue() + "\n"));
                writer.flush();
            }
            // 5.关闭输出流
            writer.close();
            writer.close();
            System.out.println("file wite success");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("io word count app success");

}
}